﻿using Bank;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BankSystem
{    
    public class BigMoneyArgs
    {
        public string Id { get; set; }
        public int Fetch { get; set; }
    }
    public delegate void BigMoneyHandler(object sender, BigMoneyArgs args);
    
    internal class ATM:WithDraw
    {
        private event BigMoneyHandler BigMoneyFetched;
        public int numOfMoney { get; set; }
        private void Warning(object sender, BigMoneyArgs args)
        {
            Console.WriteLine($"用户{args.Id}试图取出大笔金额：{args.Fetch}元");
        }
        public ATM(int numOfMoney) 
        { 
            this.numOfMoney = numOfMoney;// ATM机中的钱的数量
            BigMoneyFetched += Warning;
        }
        public void WithDraw(string id,int amount)
        {
            int fetch = Math.Min(numOfMoney * 100, amount);
            int realId = Array.IndexOf(AccountBase.ids, id);
            fetch = Math.Min(fetch, AccountBase.accounts[realId].maxwithdraw); // 取多少钱
            BigMoneyArgs args = new BigMoneyArgs() { Id = id, Fetch = fetch};
            if(fetch > 10000) // 触发事件：试图取出大额钞票
            {
                BigMoneyFetched(this, args);
            }
            fetch = fetch / 100; // 百元钞票数量。
            // 取钱            
            int fetching = 0;
            try
            {
                // 正在取钱
                Random random = new Random();
                for (; fetching < fetch; fetching++)                {
                    
                    double rate = random.NextDouble();
                    if (rate <= Bank.badRate)
                    {
                        throw new BadCashException("出现坏钞票", id, fetching);
                    }
                }
                // 取出钱。
                numOfMoney -= fetch;
                AccountBase.accounts[realId].balance -= fetch * 100; // 每张钞票100元。
                Console.WriteLine($"用户{id}取钱完成，取出{fetch*100}元，没有坏钞。");
            }
            catch (BadCashException e)
            {
                Console.WriteLine($"用户{e.Id}取出了{e.Money * 100}元。在取出第{e.Money + 1}张钞票时，遇到坏钞。");
            }           
        }
    }
}
